﻿<?php

/**
 * home actions.
 *
 * @package    costabravasfr
 * @subpackage home
 * @author     Your name here
 * @version    SVN: $Id: actions.class.php 12479 2008-10-31 10:54:40Z fabien $
 */
class homeActions extends sfActions
{
	public function executeActiveLocations(sfWebRequest $request){
	sfProjectConfiguration::getActive()->loadHelpers(array('I18N'));
	$this->response->addMeta('language', $this->getUser()->getLangCulture());
	$this->response->addMeta('description', __("slogan"));
	$this->response->addMeta('title', __("WebTitle"));
	if (!$request->getParameter('sf_culture'))
	  {
		if ($this->getUser()->isFirstRequest())
		{
		  $culture = $request->getPreferredCulture(array('en', 'ca', 'es', 'nl', 'de', 'it'));
		  $this->getUser()->setCulture($culture);
		  $this->getUser()->isFirstRequest(false);
		}
		else
		{
		  $culture = $this->getUser()->getCulture();
		}
	 
    $this->redirect('homepage');
  }
	
		$this->form = new SearcherForm();
		$from = "2000-01-01";
		$nextWeek = "2100-01-01";
		$request->setParameter('crit', 'orderId');	
		$request->setParameter('order', 'asc');
		
		$query = Doctrine::getTable('ViviendasAlquileres')->createQuery('a')
		->where('a.activo = ?', '1')
		->andWhere('a.usuario_id = ?', sfConfig::get('app_id_agency'))
		->orderBy('a.orderId');
		//->orderBy('precioMin desc');
		$this->logMessage("Entra en todas ", "info");
		$request->setParameter('personnes', 1);
		$request->setParameter('piscine', 0);
		$request->setParameter('from_date', 0);	
		$request->setParameter('semaines', 1);
		$request->setParameter('appt_villa', 2);
		//$request->setParameter('semaines', 1);
				
		$this->nbViviendas = $query->count();
		$this->logMessage("Num Viviendas ".$this->nbViviendas, "info");
		$this->pager = new sfDoctrinePager('ViviendasAlquileres', sfConfig::get('app_max_locations_per_page'));
		$this->pager->setPage($request->getParameter('page', 1));
		$this->pager->setQuery($query);
		
		$this->pager->init();
		$this->startDateSearcher = ViviendaAlquiler::checkMinDate();
	  }
  
	public function executeAdd(sfWebRequest $request){
		if ($request->isXmlHttpRequest()){
			//return $request->getParameter('id');
			if ($this->getUser()->isAuthenticated()){
				$url = sfContext::getInstance()->getController()->genUrl('@list_favorites_clients');
			}
			else{
				$url = sfContext::getInstance()->getController()->genUrl('@list_favorites');
			}
			$this->getUser()->addViviendaToFavorites($request->getParameter('id'));
			return $this->renderText("<span class='favoriteOK'>Ajout&eacute; &aacute; votre liste de <a href='$url' id='favorisLink'>favoris</a></span>");
		}
	}

	public function executeSupprimer(sfWebRequest $request){
		if ($request->isXmlHttpRequest()){
			$this->getUser()->deleteViviendaFavorites($request->getParameter('id'));
			
			if(($this->getUser()->numberFavorites()) <= 0){
				$this->getResponse()->setStatusCode(404, 'Ya no hay favoritos');				
				return sfView::NONE;
			}
			
			return $this->renderText("Mes favorites (".$this->getUser()->numberFavorites().")");
		}
	}
	
	public function executeSearchAutocompleteVivienda(){
		$letras = $this->getRequestParameter('nomLogement');  
		$q = Doctrine_Query::create()
			->from('ViviendasAlquileres v')
			->where('v.nombre LIKE ?', '%'.$letras.'%')
			->andWhere('v.usuario_id = ?', sfConfig::get('app_id_agency'))
			->andWhere('v.activo = ?', '1');
		$this->viviendas = $q->execute(); 
	}
	
	  public function executeSend(sfWebRequest $request)
  {
    $requestForm   = new RecepcionEmailsForm();
	 //$this->form = new ViviendasAlquileresForm($viviendas_alquileres);
	// set the form to bound status with the submitted values
    $requestForm->bind($request->getParameter('recepcion_emails'));

    if (!$requestForm->isValid()) {
		$errors = array();
        foreach ($requestForm->getErrorSchema() as $field => $error) {
            $errors[$field] = $error->getMessage();
        }	
        $this->errors = $errors;
		return $this->renderPartial('location/sendError', array('requestForm' => $requestForm));
	}
	//Save form in DB
	//$formRegister = $requestForm->save();
  // Create the mailer and message objects
try
{
   /*$text = "Message re�u de mail:".$requestForm->getValue('email')."dataINici:".$requestForm->getValue('datainici')."dataFIN:".$requestForm->getValue('datafin')."Nombre vivienda:".$requestForm->getValue('vivienda')."Mensaje: ".$requestForm->getValue('mensaje')."IP: ".$requestForm->getValue('ip')."Casas visitadas: ".$requestForm->getValue('casasvisitadas');    */     
 
    // Send
		/*$this->getMailer()->composeAndSend(
			sfConfig::get('app_email_from'),
			sfConfig::get('app_email_to'),
			'Costa Bravas\'s  - ',
			$text." id: ".$formRegister['id']
		);*/
			
			$message = Swift_Message::newInstance()
			  ->setFrom(sfConfig::get('app_email_from'))
			  ->setTo(sfConfig::get('app_email_to'))
			 // ->setCC(sfConfig::get('app_email_to_david'))
			  ->setSubject('Begur Holidays  - '.$requestForm->getValue('vivienda'))
			  ->setReplyTo($requestForm->getValue('email'))
			  //->setBody($text)
				;
				
				$message->setBody($this->getPartial('home/sendMail', array('from'=>$requestForm->getValue('email'), 'datainici'=>$requestForm->getValue('datainici'), 'datafin'=>$requestForm->getValue('datafin'), 'viviendaId'=>$requestForm->getValue('vivienda'), 'mensaje'=>html_entity_decode($requestForm->getValue('mensaje')))))->setContentType('text/html');
$this->getMailer()->send($message);
 
}
catch (Exception $e)
{
  $mailer->disconnect();
  return $this->renderText($formRegister ['email']."--Un probleme: ".$requestForm['vivienda']->render());
 
  // handle errors here
}

	return $this->renderText("<h3>".$this->getContext()->getI18N()->__('thanksContactForm',  array('%0%'=>$requestForm->getValue('vivienda'), '%1%'=>$requestForm->getValue('email')), 'messages')."</h3>");
  }

  protected function processForm(sfWebRequest $request, sfForm $form)
  {
    $form->bind($request->getParameter($form->getName()));
    if ($form->isValid())
    {
      $viviendas_alquileres = $form->save();

      $this->redirect('location/edit?id='.$viviendas_alquileres->getId());
    }
  }
  
    
  public function executeCheckEmailRecoverPassword(sfWebRequest $request){
		$q = Doctrine::getTable('Profile')->createQuery('u')->where('u.email_address = ?', $request->getParameter('email'));
		$user = $q->fetchOne();
		if($user!=null){
			$this->logMessage("User: ".$user->getLastName(), "info");
			$guardUser = $user->getUser();
			$newPassword = rand(1111, 9999);
			$guardUser->setPassword($newPassword);
			$guardUser->save();
			
			$this->getMailer()->composeAndSend(
			sfConfig::get('app_email_from'),
			"dacasanovas@gmail.com",
			'Costa Brava\'s - Recuperation du password de votre compte usuaire '.$guardUser->getUsername(),
			"  Bienvenu de nouveau sur votre compte usuaire".
			"  Voici les coordon�s qui vous permettront recuperer votres logements favoris:\n
usuaire: ".$guardUser->getUsername()."\n
password: ".$newPassword."\n

Merci beaucoup de votre confiance. 
 Costa Brava's Team"
		); 
		
			return $this->renderText(1);
		}
		else{
			return $this->renderText(0);
		}
  }
  
  /*public function executeGetSignature($request){
	if ($request->isXmlHttpRequest()){
		//Obtenemos los parametros pasarela sermepa de esta agencia
		$q = Doctrine_Query::create()
  ->from('PagossegurosOnline p')
  ->where('p.usuario_id = ?', $request->getParameter('id'))->execute();
		$pasarela = $q->getFirst();
		$message = $request->getParameter('importe').$request->getParameter('order').$pasarela->getMerchantcode().sfConfig::get('app_currency_sermepa').sfConfig::get('app_transaccion_sermepa').$request->getParameter('urlNot').$pasarela->getMerchantpassword();
		$signature = strtoupper(sha1(trim($message)));
		return $this->renderText($signature);
	}
  }*/
	  
}
